<template>
    <el-upload
        class="upload-demo"
        drag
        action="#"
        :disabled="disabled"
        :http-request="handleHttpUpload"
        :before-upload="beforeUpload"
        :on-success="uploadSuccess"
        :accept="fileType.join(',')"
        :folderName="folderName"
        :fileParam="fileParam"
        :show-file-list="false"
    >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
            拖动文件到此处或<em>点击上传</em>
        </div>
        <template #tip>
            <div class="el-upload__tip">
                请上传不超过5M的图片文件
            </div>
        </template>
    </el-upload>
</template>

<script setup lang="ts">
import { ElLoading, ElMessage } from "element-plus";
import type { UploadProps, UploadRequestOptions } from "element-plus";

interface IUploadImagesProps {
  disabled?: boolean; // 是否禁用上传组件 ==> 非必传[默认为 false]
  fileSize?: number; // 图片大小限制 ==> 非必传[默认为 3M]
  fileType?: any; // 图片类型限制 ==> 非必传[默认为 ["image/webp", "image/jpg", "image/jpeg", "image/png", "image/gif"]]
  height?: string; // 组件高度 ==> 非必传[默认为 120px]
  width?: string; // 组件宽度 ==> 非必传[默认为 120px]
  borderRadius?: string; // 组件边框圆角 ==> 非必传[默认为 6px]
  folderName?: string; // 文件夹名称
  fileParam?: string; // 文件类型[可向后端传递参数]
}

const props = withDefaults(defineProps<IUploadImagesProps>(), {
  disabled: false,
  fileSize: 5,
  fileType: ["image/webp", "image/jpg", "image/jpeg", "image/png", "image/gif"],
  height: "120px",
  width: "120px",
  borderRadius: "6px",
  folderName: "files",
  fileParam: "-1"
});

/**
 * @description 文件上传之前判断
 * @param rawFile 选择的文件
 * */
 const beforeUpload: UploadProps["beforeUpload"] = rawFile => {
  const imgSize = rawFile.size / 1024 / 1024 < props.fileSize;
  const imgType = props.fileType.includes(rawFile.type);
  if (!imgType) ElMessage.warning("上传图片不符合所需的格式🌻");
  if (!imgSize)
    setTimeout(() => {
      ElMessage.warning(`上传图片大小不能超过 ${props.fileSize}M！`);
    }, 0);
  return imgType && imgSize;
};
/**
 * @description 图片上传
 * @param options upload 所有配置项
 * */
 const handleHttpUpload = async (options: UploadRequestOptions) => {
  const loadingInstance = ElLoading.service({
    text: "正在上传",
    background: "rgba(0,0,0,.2)"
  });
  const reader = new FileReader();
  reader.onload = (e: any) => {
    const base64 = e.target.result;
    options.onSuccess(base64);
    loadingInstance.close();
  }
  reader.readAsDataURL(options.file);
};
/**
 * @description 图片上传成功
 * @param response 上传响应结果
 * @param uploadFile 上传的文件
 * */
 const emit = defineEmits<{
  "uploadFile": [value: string];
}>();
const uploadSuccess = (response: string | undefined) => {
  if (!response) return;
  emit("uploadFile", response);
  ElMessage.success("图片上传成功🌻");
};
</script>
<style lang="less" scoped>
</style>